/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.welchapps.nporganizer;

//import org.apache.commons.net.ftp.*;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.welchapps.nporganizer.NotePad.NoteColumns;

/**
 * Displays a list of notes. Will display notes from the {@link Uri}
 * provided in the intent if there is one, otherwise defaults to displaying the
 * contents of the {@link NoteProvider}
 */
public class NotesList extends Activity {
    private static final String TAG = "NotesList";
    private static final String version = "0.5.1";
    //private static final String def_title = "Nail Polish Organizer";
    private int currentPosition;
    protected ListView rowlist;
    private TextView totalCount, filterBy;
	private FTPClient ftpClient;
	private Context context;
	private boolean filtered;
	protected String line;

    /**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
        NoteColumns._ID, // 0
        NoteColumns.NAME, // 1
        NoteColumns.BRAND, // 2
        NoteColumns.COLLECTION, // 3
        NoteColumns.COLOR, // 4
        NoteColumns.FINISH, // 5
        NoteColumns.STATUS, // 6
        NoteColumns.ADDNOTE, // 7
        NoteColumns.IMG // 8
    };
  
    
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateNeeded = new Runnable() {
        public void run() {
        	AlertDialog.Builder builder = new AlertDialog.Builder(context);
        	builder.setTitle("New Version Available");
        	builder.setMessage("Download version "+line+" from:\n"+
        			"https://sites.google.com/site/welchapps/");
	        builder.setPositiveButton("Ok", new OnClickListener() {
	                public void onClick(DialogInterface dialog, int arg1) {
	                    dialog.dismiss();
	                }});
	        builder.setNegativeButton("Open Page", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                	Intent intent = new Intent();
                	intent.setAction(Intent.ACTION_VIEW);
        			intent.setData(Uri.parse("https://sites.google.com/site/welchapps/nail-polish-organizer"));
        			startActivity(intent);
                }});
	        builder.create().show();
        }
    };
    
    final Runnable mImportNeeded= new Runnable() {
        public void run() {
        	AlertDialog.Builder builder = new AlertDialog.Builder(context);
        	builder.setTitle("Update list");
        	builder.setMessage("A new list has been uploaded for this device. Would you like to import it?");
	        builder.setPositiveButton("Yes", new OnClickListener() {
	                public void onClick(DialogInterface dialog, int arg1) {
	                	importListFTP();
	                }});
	        builder.setNegativeButton("No", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                	dialog.dismiss();
                }});
	        builder.create().show();
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        context = this;
        setContentView(R.layout.noteslist);
        rowlist = (ListView) findViewById(R.id.rowlist);
        totalCount = (TextView) findViewById(R.id.totalCount);
        filterBy = (TextView) findViewById(R.id.FilterBy);
        
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
        

        
        //setup settings
        final String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	final Integer runs = settings.getInt("runs",0);
    	SharedPreferences.Editor editor = settings.edit();
    	// if (!settings.getString("version",version).equals(version)) {updateWelcome();}
		editor.putString("version", version);
    	editor.putInt("runs",runs+1);
    	if(settings.getString("id_key","null").equals("null")) editor.putString("id_key", android_id);
    	editor.commit();
    	
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        final String action = intent.getAction();
        if (intent.getData() == null || Intent.ACTION_VIEW.equals(action)) {
            intent.setData(NoteColumns.CONTENT_URI);
        }

        if(Intent.ACTION_VIEW.equals(action)){

        	saveFile(intent.getData());
        }
        
        //check for correct version and new import
        updateCheck();

    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // If we didn't have any trouble retrieving the data, it is now
        // time to get at the stuff.
        SharedPreferences settings = getSharedPreferences("filterPref",0);
        SharedPreferences defSettings = getSharedPreferences("defSettings",0);
        String value = settings.getString("value","");      
        String cat = settings.getString("category","None");  
        String status = settings.getString("status","Both");
        String sort = defSettings.getString("sort_order",NoteColumns.NAME_SORT_ORDER);
    	final Cursor cursor;	
    	filterBy.setText("");
    	
    	String sel_cat = "";
    	String sel_stat = "";
    	if(!cat.equals("None") && !value.equals("")){
    		sel_cat = cat.toLowerCase() + " LIKE '" + value + "%'";
    		filterBy.setText(cat + ": " + value);
    	}
    	
    	if(!status.equals("Both")){
    		sel_stat = NoteColumns.STATUS + "='" + status + "'";
    	}
    	
    	if(sel_stat.equals("") && sel_cat.equals("")){
        	cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
      			  sort);	
        	filtered = false;
        	//setTitle(def_title); 
        	//menu_filter.setIcon(R.drawable.collections_sort_off);
        	
    	}else if(!sel_stat.equals("") && !sel_cat.equals("")){
        	cursor = managedQuery(getIntent().getData(), PROJECTION, sel_stat + " AND " + sel_cat, null,
        			  sort);	
        	filtered = true;
          	//setTitle(def_title + ": Filtered");   
          	//menu_filter.setIcon(R.drawable.collections_sort_on);
    	}else{
        	cursor = managedQuery(getIntent().getData(), PROJECTION, sel_stat + sel_cat, null,
      			  sort);	
        	filtered = true;
        	//menu_filter.setIcon(R.drawable.collections_sort_on);
        	//setTitle(def_title + ": Filtered");       		
    	}

    	//Reset options menu
    	invalidateOptionsMenu();
    	
        totalCount.setText("Total Count: " + cursor.getCount());

        // Used to map notes entries from the database to views
        
        MyCursorAdapter adapter = new MyCursorAdapter(this, cursor);

        rowlist.setAdapter(adapter);
    	// setup listener for list clicking
        rowlist.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), arg3);
                
                String action = getIntent().getAction();
                if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
                    // The caller is waiting for us to return a note selected by
                    // the user.  The have clicked on one, so return it now.
                    setResult(RESULT_OK, new Intent().setData(noteUri));
                } else {
                    // Launch activity to view/edit the currently selected item
                    startActivity(new Intent(Intent.ACTION_EDIT, noteUri));
                }
			}
            
        });
        rowlist.setSelection(currentPosition);

    }
    
    @Override
    protected void onPause() {
        super.onPause();
        currentPosition = rowlist.getFirstVisiblePosition();
    }   
    
    @Override
    protected void onStop(){
    	super.onStop();
    	SharedPreferences settings = getSharedPreferences("defSettings",0);
		if(settings.getBoolean("new_upload", false) && settings.getBoolean("auto_sync", false) && settings.getBoolean("web_sync", false)){
			exportListFTP(false);
		}

    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_options_menu, menu);
        


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { 
    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	boolean web = settings.getBoolean("web_sync",false);
        switch (item.getItemId()) {
        case R.id.menu_add:
        	addItem(null);
        	return true;
        case R.id.menu_filter:
        	filterItem(null);
        	return true;
        case R.id.menu_export:
        	if(web) exportListFTP(true);
        	else exportListFile();
        	//exportListEmail();
        	return true;
        case R.id.menu_import:
        	if (web) importListFTP();
        	else importListFile();
        	return true;     
        case R.id.menu_settings:
        	startActivity(new Intent(this, QuickPrefsActivity.class));
        	return true;
        case R.id.menu_about:
        	showAbout(this);
        	return true;
        default: 
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterView.AdapterContextMenuInfo info;
	    try {
	         info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
	    } catch (ClassCastException e) {
	        Log.e(TAG, "bad menuInfo", e);
	        return false;
	    }
	    
	    Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id);
	
	    switch (item.getItemId()) {
	    case R.id.context_open:
	        // Launch activity to view/edit the currently selected item
	        startActivity(new Intent(Intent.ACTION_EDIT, noteUri));
	        return true;
	    case R.id.context_delete:
	        // Delete the note that the context menu is for
	        getContentResolver().delete(noteUri, null, null);
	        return true;
	    default:
	        return super.onContextItemSelected(item);
	    }
	}

    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        MenuItem menu_filter = menu.findItem(R.id.menu_filter);
        if (filtered == false){
       	 menu_filter.setIcon(R.drawable.collections_sort_off);
        }else{
       	 menu_filter.setIcon(R.drawable.collections_sort_on);
        }    	
		return true;
    	
    }
    
    private void updateWelcome(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	builder.setTitle("Version: "+version);
    	builder.setMessage("This update includes the ability to automatically syncronize accross devices. " +
    			"The setting is enabled by default in the settings menu. " + 
    			"This feature uses a small amount of data everytime the application is started. " +
    			"Press OK to perform the inital export (needed for this feature to work).");
        builder.setPositiveButton("Ok", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                    exportListFTP(true);
                }});
        builder.setNegativeButton("Cancel", new OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
            }});
        builder.create().show();
    }
    
	private void updateCheck(){
    	new Thread(){
    		public void run(){
    			//setup settings
    	    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	    	final boolean update = settings.getBoolean("update_notify",true);
    	    	final boolean autosync = settings.getBoolean("auto_sync",true);
    			//check for update
    	    	if (update){
	    	        try {     
	    				URLConnection Url = new URL("https://sites.google.com/site/welchapps/version.txt").openConnection();
	    				BufferedReader reader = new BufferedReader(new InputStreamReader(Url.getInputStream(), "UTF-8")); 
	    				line = reader.readLine();
	
	    				if (!line.equals(version)) mHandler.post(mUpdateNeeded);
	    					
	    			} catch (MalformedURLException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			} catch (UnsupportedEncodingException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			} catch (IOException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    	        }
    	        //check for new import
    	        if (autosync) {
    	        	if (ftpConnect("66.67.54.97", "ericwelch08", "5q2cxoSKMjJ9tLP4HU63", 2221)){       

    	            	String serverTime;
						try {
							serverTime = ftpClient.getModificationTime("/"+settings.getString("id_key","null")+".csv").substring(4,18);
	    	            	String storeTime = settings.getString("upload_time","null").substring(4,18);
	    	            	if (!storeTime.equals("null") && !serverTime.equals("null")){
	    	            		if (!serverTime.equals(storeTime)){
	    	            			 mHandler.post(mImportNeeded);
	    	            		}
	    	            	}

	    	        		ftpDisconnect();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						 catch (NullPointerException e){
							 e.printStackTrace();
						 }
						 

    	        	}
    	        	
    	        }
    		}
    		
    	}.start();

    }
    
    public void addItem(View view){
    	startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
    }
    
    public void showAbout(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("About");
        builder.setMessage("Version: "+version+"\n\n"+
        		"Written by Eric Welch for his nail polish addicted girlfriend\n\n"+
        		"ericwelch08@gmail.com\n\n"+
        		"Features:\n"+
        		"1. Export/import to/from SD card\n"+
        		"2. Filter based on criteria\n"+
        		"3. Capture photos of polishes\n"+
        		"4. Create own/want lists\n\n"+
        		"To edit list on a PC, select 'export' from the menu on the main screen. "+
        		"This will create the 'NailPolish.csv' file on the phone's SD card. "+
        		"Edit the file on a PC with Excel or similar program. "+
        		"Import the list with the 'import' button on the menu. ");
        builder.setPositiveButton("Close", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                    dialog.dismiss();
                }});
        builder.setNegativeButton("Visit Website", new OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
            	Intent intent = new Intent();
            	intent.setAction(Intent.ACTION_VIEW);
    			intent.setData(Uri.parse("https://sites.google.com/site/welchapps/nail-polish-organizer"));
    			startActivity(intent);
            }});
        builder.setCancelable(false);
        builder.create().show();
    }
    
    public void filterItem(View view){
    	startActivity(new Intent(this, FilterList.class));
    }
       
    
    //not currently implemented
    public void exportListEmail(){
    	//Toast.makeText(this,getFilesDir().toString()+ " NailPolish.csv", 0).show();
    	Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,	NoteColumns.NAME_SORT_ORDER);
    	cursor.moveToFirst();
    	try{
    		File file = new File(getExternalFilesDir(null), "NailPolish.csv");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write("Name,Brand,Collection,Note\n");
			for(int i = 0; i<cursor.getCount(); i++){
				bw.write(cursor.getString(1)+",");
				bw.write(cursor.getString(2)+",");
				bw.write(cursor.getString(3)+",");
				bw.write(cursor.getString(4));
				bw.write("\n");
				cursor.moveToNext();
			}
			bw.close();
    	} catch (IOException e) {
            e.printStackTrace();
        }
    	Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
    	emailIntent.setType("text/plain");
        // emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"ericwelch08@gmail.com"}); 
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Nail Polish Organizer File"); 
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Nail Polish Organizer File"); 
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+getExternalFilesDir(null).toString()+ "/NailPolish.csv"));
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));

    }
 
    public void exportListFile(){
    	//Toast.makeText(this,getFilesDir().toString()+ " NailPolish.csv", 0).show();
    	Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,	NoteColumns.NAME_SORT_ORDER);
    	cursor.moveToFirst();
    	try{
    		File file = new File(Environment.getExternalStorageDirectory(), "NailPolish.csv");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write("Name,Brand,Collection,Color,Finish,Status,Note,DO NOT EDIT\n");
			for(int i = 0; i<cursor.getCount(); i++){
				bw.write(cursor.getString(1)+",");
				bw.write(cursor.getString(2)+",");
				bw.write(cursor.getString(3)+",");
				bw.write(cursor.getString(4)+",");
				bw.write(cursor.getString(5)+",");
				bw.write(cursor.getString(6)+",");
				bw.write(cursor.getString(7)+",");
				bw.write(cursor.getString(8));
				bw.write("\n");
				cursor.moveToNext();
			}
			bw.close();
			Toast.makeText(this,"Successfully exported list to: "+Environment.getExternalStorageState()+"/NailPolish.csv", Toast.LENGTH_LONG).show();
    	} catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this,"Unable to export list. Check SD card.", Toast.LENGTH_LONG).show();
    	}

    }
    
    
    
    public void exportListFTP(final boolean showDialog){
    	final ProgressDialog progressDialog = ProgressDialog.show(this, "", "Exporting...");
    	new Thread() 
    	{
    	  public void run() 
    	  {

    	     try
    	       {
    	     	Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,	NoteColumns.NAME_SORT_ORDER);
    	    	cursor.moveToFirst();
    	    	try{
    	    		if(ftpConnect("66.67.54.97", "ericwelch08", "5q2cxoSKMjJ9tLP4HU63", 2221)){  
	    	    		File file = new File(getExternalFilesDir(null), "NailPolish.csv");
	    				if (!file.exists()) {
	    					file.createNewFile();
	    				}
	    				FileWriter fw = new FileWriter(file.getAbsoluteFile());
	    				BufferedWriter bw = new BufferedWriter(fw);
	    				bw.write("Name,Brand,Collection,Color,Finish,Status,Note,DO NOT EDIT\n");
	    				for(int i = 0; i<cursor.getCount(); i++){
	    					
	    					bw.write(cursor.getString(1)+",");
	    					bw.write(cursor.getString(2)+",");
	    					bw.write(cursor.getString(3)+",");
	    					bw.write(cursor.getString(4)+",");
	    					bw.write(cursor.getString(5)+",");
	    					bw.write(cursor.getString(6)+",");
	    					bw.write(cursor.getString(7)+",");
	    					bw.write(cursor.getString(8)+",");
	    					//bw.write(cursor.getString(8));
	    					bw.write("\n");
	    					cursor.moveToNext();
	    				}
	    				bw.close();
        	    	
        	        	if(ftpUpload(getExternalFilesDir(null)+"/","NailPolish.csv","/")){
        	        		if (showDialog) {Toast.makeText(getBaseContext(),"Successfully exported list", Toast.LENGTH_LONG).show();}
        	        	}else if (showDialog) {Toast.makeText(getBaseContext(),"Unable to upload file", Toast.LENGTH_LONG).show();}
        	        	ftpDisconnect();
        	    	}else if (showDialog) {Toast.makeText(getBaseContext(),"Unable to connect to FTP server", Toast.LENGTH_LONG).show();}
    	    	} catch (IOException e) {
    	            e.printStackTrace();
    	            if (showDialog) {Toast.makeText(getBaseContext(),"Unable to export list. Check SD card.", Toast.LENGTH_LONG).show();}
    	    	}
    	     	

    	      }
    	    catch (Exception e)
    	    {
    	        Log.e("tag",e.getMessage());
    	    }
    	// dismiss the progressdialog   
    	     progressDialog.dismiss();
    	 }
    	}.start();


    	
    }
    
    
    public void importListFTP(){
    	final String dstfile = getExternalFilesDir(null)+"/NailPolish.csv";
    	final ProgressDialog progressDialog = ProgressDialog.show(this, "", "Importing...");
    	new Thread() 
    	{
    	  public void run() 
    	  {

    	     try
    	       {
    	     	if(ftpConnect("66.67.54.97", "ericwelch08", "5q2cxoSKMjJ9tLP4HU63", 2221)){  		
    	        	if(ftpDownload(dstfile)){
    	            	
    	        	}else Toast.makeText(getBaseContext(),"Unable to download file", Toast.LENGTH_LONG).show();
    	        	ftpDisconnect();
    	    	}else Toast.makeText(getBaseContext(),"Unable to connect to FTP server", Toast.LENGTH_LONG).show();

    	    	try {
    	        	getContentResolver().delete(getIntent().getData(), null, null);
    	    		BufferedReader in = new BufferedReader(new FileReader(getExternalFilesDir(null)+"/NailPolish.csv"));
    	    		String reader = "";
    	    		reader = in.readLine();
    	    		while ((reader = in.readLine()) != null){
    	                String[] RowData = reader.split(",");
    	                ContentValues values = new ContentValues();
    	                values.put(NoteColumns.NAME, RowData[0]);
    	                values.put(NoteColumns.BRAND, RowData[1]);
    	                values.put(NoteColumns.COLLECTION, RowData[2]);
    	                values.put(NoteColumns.COLOR, RowData[3]);
    	                values.put(NoteColumns.FINISH, RowData[4]);
    	                values.put(NoteColumns.STATUS, RowData[5]);
    	                values.put(NoteColumns.ADDNOTE, RowData[6]);
    	                values.put(NoteColumns.IMG, RowData[7]);
    	                getContentResolver().insert(NoteColumns.CONTENT_URI, values);
    	    		}
    	    		in.close();
    	    		totalCount.setText("Total Count: " + managedQuery(getIntent().getData(), PROJECTION, null, null, NoteColumns.NAME_SORT_ORDER).getCount());
    	    		} catch (IOException e) {
    	    			e.printStackTrace();
    	    			Toast.makeText(getBaseContext(),"Unable to find file", Toast.LENGTH_LONG).show();
    	    		}   
    	      }
    	     
    	    catch (Exception e)
    	    {
    	        Log.e("tag",e.getMessage());
    	    }
    	// dismiss the progressdialog   
    	    progressDialog.dismiss();
    	 }
    	}.start();



    	
    }
	
    
    public void importListFile(){
    	try {
    	getContentResolver().delete(getIntent().getData(), null, null);
		BufferedReader in = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory()+"/NailPolish.csv"));
		String reader = "";
		reader = in.readLine();
		while ((reader = in.readLine()) != null){
            String[] RowData = reader.split(",");
            ContentValues values = new ContentValues();
            values.put(NoteColumns.NAME, RowData[0]);
            values.put(NoteColumns.BRAND, RowData[1]);
            values.put(NoteColumns.COLLECTION, RowData[2]);
            values.put(NoteColumns.COLOR, RowData[3]);
            values.put(NoteColumns.FINISH, RowData[4]);
            values.put(NoteColumns.STATUS, RowData[5]);
            values.put(NoteColumns.ADDNOTE, RowData[6]);
            values.put(NoteColumns.IMG, RowData[7]);
            getContentResolver().insert(NoteColumns.CONTENT_URI, values);
		}
		Toast.makeText(this,"Successfully imported list", Toast.LENGTH_LONG).show();
		in.close();
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(this,"Unable to find file: "+Environment.getExternalStorageState()+"/NailPolish.csv", Toast.LENGTH_LONG).show();
		}   	
    }
    
    // not currently implemented
    public void importListEmail(Intent intent){
    	Toast.makeText(this,"Uri: "+intent.getData(), Toast.LENGTH_LONG).show();

    	try {
    	getContentResolver().delete(getIntent().getData(), null, null);
		BufferedReader in = new BufferedReader(new FileReader("/mnt/sdcard/welchapps/NailPolish.csv"));
		String reader = "";
		while ((reader = in.readLine()) != null){
            String[] RowData = reader.split(",");
            String name = RowData[0];
            String coll = RowData[1];
            String brand = RowData[2];
            String note = RowData[3];
            ContentValues values = new ContentValues();
            values.put(NoteColumns.NAME, name);
            values.put(NoteColumns.COLLECTION, coll);
            values.put(NoteColumns.BRAND, brand);
            values.put(NoteColumns.ADDNOTE, note);
            getContentResolver().insert(NoteColumns.CONTENT_URI, values);
		}
		Toast.makeText(this,"Successfully imported list", Toast.LENGTH_LONG).show();
		in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}   	
    }
    
    public boolean ftpConnect(String host, String username,
            String password, int port){
		try {
			ftpClient = new FTPClient();
			// connecting to the host
			ftpClient.connect(host, port);
			
			// now check the reply code, if positive mean connection success
			if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				// login using username & password
				boolean status = ftpClient.login(username, password);

				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				ftpClient.enterLocalPassiveMode();
				
				return status;
			}
		} catch(Exception e) {
			Log.d(TAG, "Error: could not connect to host " + host );
		}
		
		return false;
    }
    
    public boolean ftpDisconnect()
    {
        try {
            ftpClient.logout();
            ftpClient.disconnect();
            return true;
        } catch (Exception e) {
            Log.d(TAG, "Error occurred while disconnecting from ftp server.");
        }

        return false;
    }
    
    public boolean ftpDownload(String desFilePath)
    {
        boolean status = false;
        try {
        	SharedPreferences settings = getSharedPreferences("defSettings",0);        
        	String srcFile = settings.getString("id_key","null");
            FileOutputStream desFileStream = new FileOutputStream(desFilePath);
            status = ftpClient.retrieveFile("/" + srcFile + ".csv", desFileStream);
            desFileStream.close();
        	SharedPreferences.Editor editor = settings.edit();
    		editor.putString("upload_time", ftpClient.getModificationTime("/"+settings.getString("id_key","null")+".csv"));
    		editor.putBoolean("new_upload",false);
        	editor.commit();

            return status;
        } catch (Exception e) {
            Log.d(TAG, "download failed");
        }

        return status;
    }
    

    public boolean ftpUpload(String srcFilePath, String desFileName,
                             String desDirectory)
    {
        boolean status = false;
        try {
            	SharedPreferences settings = getSharedPreferences("defSettings",0);            
            	FileInputStream srcFileStream = new FileInputStream(srcFilePath+desFileName);

            // change working directory to the destination directory
            //if (ftpChangeDirectory(desDirectory)) {
            	String dest = settings.getString("id_key","null")+".csv";
                status = ftpClient.storeFile(dest, srcFileStream);

            	SharedPreferences.Editor editor = settings.edit();
        		editor.putString("upload_time", ftpClient.getModificationTime("/"+settings.getString("id_key","null")+".csv"));
        		editor.putBoolean("new_upload",false);
            	editor.commit();
            //}

            srcFileStream.close();
            return status;
        } 
        catch (Exception e) {
            Log.d(TAG, "upload failed");
        }

        return status;
    }


    //not currently implemented
    void saveFile(Uri uri)
	{

	    String destinationFilename = getExternalFilesDir(null).getPath() + "/NP.csv";
	    File file = new File(uri.getPath());
	
	    BufferedInputStream bis = null;
	    BufferedOutputStream bos = null;
	
	    try {
	      bis = new BufferedInputStream(new FileInputStream(file));
	      bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
	      byte[] buf = new byte[1024];
	      bis.read(buf);
	      do {
	        bos.write(buf);
	      } while(bis.read(buf) != -1);
	    } catch (IOException e) {
	
	    } finally {
	      try {
	        if (bis != null) bis.close();
	        if (bos != null) bos.close();
	      } catch (IOException e) {
	
	      }
	    }
	}
	
}




